<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------


namespace app\adminapi\controller\room;


use app\adminapi\controller\BaseAdminController;
use app\adminapi\lists\room\RoomHospitalLists;
use app\adminapi\logic\room\RoomHospitalLogic;
use app\adminapi\validate\room\RoomHospitalValidate;
use app\common\model\Building;
use app\common\model\Campus;
use app\common\model\room\RoomHospital;
use app\common\model\room\RoomHospitalDevice;
use app\common\model\room\RoomHospitalDeviceLog;
use app\common\model\room\RoomHospitalLog;
use app\common\model\room\RoomHospitalUser;
use Overtrue\Pinyin\Pinyin;
use think\Db;


/**
 * 全院房间管理控制器
 * Class RoomHospitalController
 * @package app\adminapi\controller\room
 */
class RoomHospitalController extends BaseAdminController {

    /**
     * @notes 获取全院房间管理列表
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function lists() {
        return $this->dataLists(new RoomHospitalLists());
    }

    public function searchLists() {
        $month_list = [];
        $max_y = date("Y");
        $max_m = 12;
        for ($y = 2024; $y <= $max_y; $y++) {
            if ($y == $max_y) {
                $max_m = date("m");
            }
            for ($m = 1; $m <= $max_m; $m++) {
                if ($m < 10) {
                    $month_list[$y . 0 . $m] = [
                        "name" => $y . '年' . 0 . $m . '月',
                        "id" => $y . 0 . $m,
                    ];
                } else {
                    $month_list[$y . $m] = [
                        "name" => $y . '年' . $m . '月',
                        "id" => $y . $m,
                    ];
                }
            }
        }

        $cid = $this->adminCid;

        $c_where = [];
        $c_where[] = ["status", "=", 1];
        if ($cid !== 0) {
            $c_where[] = ["id", "=", $cid];
        }

        $b_where = [];
        $b_where[] = ["status", "=", 1];
        if ($cid !== 0) {
            $b_where[] = ["cid", "=", $cid];
        }

        return $this->success('', [
            "month_list" => array_reverse($month_list),
            "campus_list" => Campus::where($c_where)->select()->toArray(),
            "building_list" => Building::where($b_where)->select()->toArray(),
            "cb_lists" => Campus::field([
                "id", "name",
                "id as value",
                "name as label",
            ])->where($c_where)->with(["building" => function ($q) use ($b_where) {
                $q->field([
                    "id", "name", "cid", "id as value", "name as label",
                ])->where($b_where);
            }])->select()->each(function ($item) {
                $item->children = $item['building'];
                unset($item['building']);
                return $item;
            })->toArray(),
            "type_list" => RoomHospital::getTypeList(),
            "lift_list" => RoomHospital::getLiftList(),
        ], 1, 1);
    }

    /**
     * @notes 添加全院房间管理
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function add() {
        $params = (new RoomHospitalValidate())->post()->goCheck('add');
        $result = RoomHospitalLogic::add($params);
        if (true === $result) {
            return $this->success('添加成功', [], 1, 1);
        }
        return $this->fail(RoomHospitalLogic::getError());
    }


    /**
     * @notes 编辑全院房间管理
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function edit() {
        $params = (new RoomHospitalValidate())->post()->goCheck('edit');
        $result = RoomHospitalLogic::edit($params);
        if (true === $result) {
            return $this->success('编辑成功', [], 1, 1);
        }
        return $this->fail(RoomHospitalLogic::getError());
    }

    /**
     * @notes 删除全院房间管理
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function delete() {
        $params = (new RoomHospitalValidate())->post()->goCheck('delete');
        RoomHospitalLogic::delete($params);
        return $this->success('删除成功', [], 1, 1);
    }


    /**
     * @notes 获取全院房间管理详情
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function detail() {
        $params = (new RoomHospitalValidate())->goCheck('detail');
        $result = RoomHospitalLogic::detail($params);
        return $this->data($result);
    }

    /**
     * @notes 获取全院房间更新费用
     */
    public function updateFee() {
        $blist = Building::where([
            ["status", "=", "1"],
        ])->where(function ($query) {
            $query->whereOr([
                ["all_lift_fee", ">", "0"],
                ["all_second_pressure_fee", ">", "0"],
            ]);
        })->select()->toArray();

        $db = new Db();
        $bids = [];
        foreach ($blist as $v) {
            $rh_ids = RoomHospital::where("status", 1)->where("bid", $v['id'])->whereNotIn("type", [0])->column("id");
            $all_lift_type = RoomHospital::where("status", 1)->where("bid", $v['id'])->whereNotIn("type", [0])->sum('lift_type');
            RoomHospital::whereIn("id", $rh_ids)->where("bid", $v['id'])->whereNotIn("type", [0])->update([
                "second_pressure_fee" => $db->raw($v['all_second_pressure_fee'] . "/" . count($rh_ids)),
                "lift_fee" => $db->raw("lift_type/" . $all_lift_type . "*" . $v['all_lift_fee']),
            ]);
            $bids[] = $v['id'];
        }
        Building::whereIn("id", $bids)->update([
            "is_month_begin" => 1,
        ]);
        return $this->data($blist);
    }


    /**
     * @notes 全院房间月初始化
     */
    public function newMonth() {
        set_time_limit(0);
        ini_set("max_execution_time", 30000);

        $data = [
//            "ym" => date("Ym"),
            "ym" => 202404,
//            "this_time" => date("Y-m-d H:i:s"),
            "this_time" => date("2024-04-25 H:i:s"),
            "db" => new Db(),
        ];

        if (RoomHospitalUser::where('log_date', $data['ym'])->count() > 0) {
            return $this->success('已初始化', [], 1, 1);
        }

//        // 住户房间设备记录
        $user_save = RoomHospital::field([
            "cid", "bid",
            "user_id", "user_name", "user_mobile",
            "GROUP_CONCAT(id) as room_ids",
            "sum(lift_fee) as all_lift_fee",
            "sum(second_pressure_fee) as all_second_pressure_fee",
            "count(id) as room_count",
            "'" . $data['this_time'] . "' as add_time",
            "'" . $data['this_time'] . "' as update_time",
            "'" . $data['this_time'] . "' as log_time",
            "'" . $data['ym'] . "' as log_date",
        ])->where([
            ["status", "=", 1],
            ["user_id", ">", 0],
        ])->with([
            "user", "user_all_room",
        ])->group('user_id')->select()->toArray();
        $user_save = (new RoomHospital())->data_append($user_save);
        (new RoomHospitalUser())->saveAll($user_save);
//        var_dump($user_save);exit;


        $room_save = RoomHospital::field([
            "*",
            "id as rid",
            "lift_fee as room_lift_fee",
            "second_pressure_fee as room_second_pressure_fee",
            "'" . $data['ym'] . "' as log_date",
            "'" . $data['this_time'] . "' as log_time",
        ])->where([
            ["status", "=", 1],
        ])->with([
            "allDevice",
        ])
            ->with([
                "campus", "building", // "allDevice",
            ])
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_s_use_total';
                $query->where('device_type', 1);
            }], "use_total")
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_s_price';
                $query->where('device_type', 1);
            }], "price")
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_s_total_fee';
                $query->where('device_type', 1);
            }], "total_fee")
            ->withCount(["allDevice" => function ($query, &$alias) {
                $alias = 'room_s_device_count';
                $query->where('device_type', 1);
            }])
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_d_use_total';
                $query->where('device_type', 2);
            }], "use_total")
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_d_price';
                $query->where('device_type', 2);
            }], "price")
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_d_total_fee';
                $query->where('device_type', 2);
            }], "total_fee")
            ->withCount(["allDevice" => function ($query, &$alias) {
                $alias = 'room_d_device_count';
                $query->where('device_type', 2);
            }])
            ->withSum(["allDevice" => function ($query, &$alias) {
                $alias = 'room_all_total_fee';
            }], "total_fee")
            ->append([
                "user",
            ])->select()->each(function ($item) {
                unset($item['id']);
                return $item;
            })->toArray();
        foreach ($room_save as $k => &$item) {
            $item['cname'] = $item['campus']['name'] ?? '';
            $item['bname'] = $item['building']['name'] ?? '';

            $item['room_all_total_fee'] = sprintf("%.6f", $item['room_all_total_fee'] + $item['room_lift_fee'] + $item['room_second_pressure_fee']);

            $item['user_ids'] = $item['user_id'];
            $item['user_count'] = 1;
            $item['user'] = json_encode($item['user'], JSON_UNESCAPED_UNICODE);
//            $item->user = json_encode([[
//                "id" => $item['user_id'], "user_id" => $item['user_id'], "user_name" => $item['user_name'], "user_mobile" => $item['user_mobile'],
//            ]], JSON_UNESCAPED_UNICODE);
        }
//        var_dump($room_save);exit;
        (new RoomHospitalLog())->saveAll($room_save);


        // 房间设备记录
        $rhd_lists = RoomHospitalDevice::alias('a')->field([
            "a.cid", "a.bid", "a.rid", "a.id as log_id",
            "a.device_id", "a.device_type", "a.device_name", "a.device_no",
            "a.coefficient", "a.price",
            "a.base_number", "IF(a.reading is null, a.base_number, a.reading) as reading",
            "a.use_total", "a.total_fee",
            "'" . $data['this_time'] . "' as log_time", "{$data['ym']} as log_date",
            "a.log_time as reading_time",
            // "device.type as device_type",
        ])->join("device", "device_id = device.id", "left")->where([
            ["a.status", "=", 1],
        ])->select()->toArray();
        (new RoomHospitalDeviceLog())->saveAll($rhd_lists);
//        var_dump($rhd_lists);exit;


//        // 房间数据情况
//        RoomHospitalDevice::where([
//            ["status", "=", 1],
//        ])->update([
//            "base_number" => $data['db']->raw("reading"),
//            "use_total" => 0,
//            "total_fee" => 0,
//            "log_time" => null,
//            "update_time" => date("Y-m-d H:i:s"),
//            "lift_fee" => 0, // 电梯费
//            "second_pressure_fee" => 0, // 二次压力费
//        ]);
//
//
//        // 房间数据清空
//        RoomHospital::where([
//            ["status", "=", 1],
//        ])->update([
//            "lift_fee" => 0, // 电梯费
//            "second_pressure_fee" => 0, // 二次压力费
//            "update_time" => date("Y-m-d H:i:s"),
//        ]);


        return $this->success('操作成功', [], 1, 1);
    }

}
